"""
	Developerd by Andrea Stagi <stagi.andrea@gmail.com>
	TwittLine - the client twitter on your terminal
	Copyright (C) 2010 Andrea Stagi

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import modules.tweepy
from modules.tweepy import *
import modules.tweepy.error
import blowfish
from modules import twittutils
from modules import twittconsts
from modules.graphic import twittcolor
from hashlib import sha256
import pickle
import os

def getApi():

    conn=False
    errmsg=""

    while (conn==False):

	    if(errmsg!=""):
            	twittcolor.colorprintln("\n"+errmsg,0)
		print "";

	    try:
	    	username = raw_input('Twitter username: ')
	    except:
		twittcolor.colorprintln(twittconsts.MESS_EXEPCTRLC,0)
		return 0;
	    
	    print "Twitter password:",
	    password = twittutils.getPassword()

	    cipher = blowfish.Blowfish(sha256('key').digest()) 
	    cipher.initCTR() 
		
	    if(os.name=="posix"):
			consumer=cipher.decryptCTR(pickle.load(open(os.path.dirname(__file__) + '/twitthings.twl', 'rb'))) 
	    else:
	        consumer=cipher.decryptCTR(pickle.load(open('\\twitthings.twl', 'rb'))) 

	    twittcolor.colorprintln("\n\nTrying login...Please wait...",1)

#	    auth = tweepy.OAuthHandler(consumer[0:21], consumer[22:len(consumer)])
	    auth = OAuthHandler(consumer[0:21], consumer[22:len(consumer)])

	    try:
	    	token = auth.get_xauth_access_token(username, password)
	    except error.TweepError as details:
		errmsg="" + details.reason
	    else:
		conn=True
	    
	    continue

    auth.set_access_token(token.key, token.secret)

    return API(auth)
